package com.spring.sso.controller;

import com.alibaba.fastjson.JSON;
import com.spring.sso.common.CommonResult;
import com.spring.sso.common.DefaultUserDetails;
import com.spring.sso.config.AuthenticationConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : pangfuzhong
 * @description
 * @date : 2021/9/18 14:52
 */
@Slf4j
@RestController
public class LoginAuthenticationController {

    @Autowired
    private AuthenticationConfig authenticationConfig;

    @PostMapping("/ssoLogin")
    public void ssoLogin(HttpServletRequest request, HttpServletResponse response) {

    }

    @PostMapping("/unifiedLoginSuccess")
    public void formLoginSuccess(HttpServletRequest request, HttpServletResponse response) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
        String accessToken = auth.getDetails().toString();
        this.authenticationConfig.getConfigMap().put(this.authenticationConfig.getAppName(), accessToken);

        response.setContentType("application/json; chartset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().write(JSON.toJSONString(CommonResult.success(accessToken)));
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            SecurityContextHolder.clearContext();
        }
    }

    @PostMapping("/unifiedLoginFailure")
    public void formLoginFailure(HttpServletRequest request, HttpServletResponse response) {

    }
}
